package com.fruitshop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fruitshop.dto.OrderCreateDTO;
import com.fruitshop.entity.Address;
import com.fruitshop.entity.Fruit;
import com.fruitshop.entity.Order;
import com.fruitshop.entity.OrderItem;
import com.fruitshop.exception.BusinessException;
import com.fruitshop.mapper.OrderItemMapper;
import com.fruitshop.mapper.OrderMapper;
import com.fruitshop.service.AddressService;
import com.fruitshop.service.CartService;
import com.fruitshop.service.FruitService;
import com.fruitshop.service.OrderService;
import com.fruitshop.vo.CartVO;
import com.fruitshop.vo.OrderItemVO;
import com.fruitshop.vo.OrderVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * 订单服务实现
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {
    
    private final OrderItemMapper orderItemMapper;
    private final AddressService addressService;
    private final CartService cartService;
    private final FruitService fruitService;
    
    /**
     * 创建订单
     *
     * @param userId         用户ID
     * @param orderCreateDTO 订单创建数据
     * @return 订单编号
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String create(Long userId, OrderCreateDTO orderCreateDTO) {
        // 1. 查询收货地址
        Address address = addressService.getDetail(userId, orderCreateDTO.getAddressId());
        
        // 2. 查询购物车中选中的商品
        List<CartVO> cartList = cartService.list(userId).stream()
                .filter(cart -> cart.getSelected() == 1)
                .collect(Collectors.toList());
        
        if (cartList.isEmpty()) {
            throw new BusinessException("请选择商品");
        }
        
        // 3. 校验库存并计算总金额
        BigDecimal totalAmount = BigDecimal.ZERO;
        List<OrderItem> orderItems = new ArrayList<>();
        
        for (CartVO cart : cartList) {
            Fruit fruit = fruitService.getById(cart.getFruitId());
            if (fruit == null) {
                throw new BusinessException("商品不存在: " + cart.getFruitName());
            }
            
            if (fruit.getIsOnSale() != 1) {
                throw new BusinessException("商品已下架: " + cart.getFruitName());
            }
            
            if (fruit.getStock() < cart.getQuantity()) {
                throw new BusinessException("商品库存不足: " + cart.getFruitName());
            }
            
            // 计算商品总价
            BigDecimal itemPrice = (fruit.getDiscountPrice() != null && fruit.getDiscountPrice().compareTo(BigDecimal.ZERO) > 0) 
                    ? fruit.getDiscountPrice() : fruit.getPrice();
            BigDecimal itemTotal = itemPrice.multiply(new BigDecimal(cart.getQuantity()));
            totalAmount = totalAmount.add(itemTotal);
            
            // 创建订单项
            OrderItem orderItem = new OrderItem();
            orderItem.setFruitId(fruit.getId());
            orderItem.setFruitName(fruit.getName());
            orderItem.setFruitImage(fruit.getImageUrl());
            orderItem.setPrice(itemPrice);
            orderItem.setQuantity(cart.getQuantity());
            orderItem.setTotalAmount(itemTotal);
            orderItems.add(orderItem);
            
            // 更新库存和销量
            fruit.setStock(fruit.getStock() - cart.getQuantity());
            fruit.setSales(fruit.getSales() + cart.getQuantity());
            fruitService.updateById(fruit);
        }
        
        // 4. 创建订单
        String orderNo = generateOrderNo();
        Order order = new Order();
        order.setOrderNo(orderNo);
        order.setUserId(userId);
        order.setTotalAmount(totalAmount);
        order.setPayAmount(totalAmount); // 实际支付金额，可以考虑优惠券等
        order.setStatus(0); // 待付款
        order.setReceiverName(address.getReceiverName());
        order.setReceiverPhone(address.getReceiverPhone());
        order.setReceiverAddress(
                address.getProvince() + " " + 
                address.getCity() + " " + 
                address.getDistrict() + " " + 
                address.getDetailAddress()
        );
        order.setCreateTime(LocalDateTime.now());
        order.setUpdateTime(LocalDateTime.now());
        save(order);
        
        // 5. 保存订单项
        for (OrderItem orderItem : orderItems) {
            orderItem.setOrderId(order.getId());
            orderItem.setOrderNo(orderNo);
            orderItem.setCreateTime(LocalDateTime.now());
            orderItem.setUpdateTime(LocalDateTime.now());
            orderItemMapper.insert(orderItem);
        }
        
        // 6. 清空购物车中选中的商品
        for (CartVO cart : cartList) {
            cartService.delete(userId, cart.getId());
        }
        
        return orderNo;
    }
    
    /**
     * 支付订单
     *
     * @param userId  用户ID
     * @param orderNo 订单编号
     * @return 是否成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean pay(Long userId, String orderNo) {
        Order order = getOne(new LambdaQueryWrapper<Order>()
                .eq(Order::getOrderNo, orderNo)
                .eq(Order::getUserId, userId));
        
        if (order == null) {
            throw new BusinessException("订单不存在");
        }
        
        if (order.getStatus() != 0) {
            throw new BusinessException("订单状态不正确");
        }
        
        order.setStatus(1); // 待发货
        order.setPayTime(LocalDateTime.now());
        order.setUpdateTime(LocalDateTime.now());
        
        return updateById(order);
    }
    
    /**
     * 取消订单
     *
     * @param userId  用户ID
     * @param orderNo 订单编号
     * @return 是否成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean cancel(Long userId, String orderNo) {
        Order order = getOne(new LambdaQueryWrapper<Order>()
                .eq(Order::getOrderNo, orderNo)
                .eq(Order::getUserId, userId));
        
        if (order == null) {
            throw new BusinessException("订单不存在");
        }
        
        if (order.getStatus() != 0) {
            throw new BusinessException("订单状态不正确，只有待付款的订单可以取消");
        }
        
        // 恢复库存和销量
        List<OrderItem> orderItems = orderItemMapper.selectList(
                new LambdaQueryWrapper<OrderItem>().eq(OrderItem::getOrderNo, orderNo));
        
        for (OrderItem orderItem : orderItems) {
            Fruit fruit = fruitService.getById(orderItem.getFruitId());
            if (fruit != null) {
                fruit.setStock(fruit.getStock() + orderItem.getQuantity());
                fruit.setSales(fruit.getSales() - orderItem.getQuantity());
                fruitService.updateById(fruit);
            }
        }
        
        order.setStatus(4); // 已取消
        order.setCancelTime(LocalDateTime.now());
        order.setUpdateTime(LocalDateTime.now());
        
        return updateById(order);
    }
    
    /**
     * 确认收货
     *
     * @param userId  用户ID
     * @param orderNo 订单编号
     * @return 是否成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean confirm(Long userId, String orderNo) {
        Order order = getOne(new LambdaQueryWrapper<Order>()
                .eq(Order::getOrderNo, orderNo)
                .eq(Order::getUserId, userId));
        
        if (order == null) {
            throw new BusinessException("订单不存在");
        }
        
        if (order.getStatus() != 2) {
            throw new BusinessException("订单状态不正确，只有待收货的订单可以确认收货");
        }
        
        order.setStatus(3); // 已完成
        order.setFinishTime(LocalDateTime.now());
        order.setUpdateTime(LocalDateTime.now());
        
        return updateById(order);
    }
    
    /**
     * 获取订单详情
     *
     * @param userId  用户ID
     * @param orderNo 订单编号
     * @return 订单详情
     */
    @Override
    public OrderVO getDetail(Long userId, String orderNo) {
        Order order = getOne(new LambdaQueryWrapper<Order>()
                .eq(Order::getOrderNo, orderNo)
                .eq(Order::getUserId, userId));
        
        if (order == null) {
            throw new BusinessException("订单不存在");
        }
        
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(order, orderVO);
        
        // 设置订单状态描述
        orderVO.setStatusDesc(getStatusDesc(order.getStatus()));
        
        // 查询订单项
        List<OrderItemVO> orderItemVOList = orderItemMapper.selectOrderItemsByOrderId(order.getId());
        orderVO.setOrderItems(orderItemVOList);
        
        return orderVO;
    }
    
    /**
     * 分页查询订单列表
     *
     * @param userId   用户ID
     * @param status   订单状态
     * @param page     页码
     * @param pageSize 页大小
     * @return 订单分页列表
     */
    @Override
    public Page<OrderVO> pageList(Long userId, Integer status, Integer page, Integer pageSize) {
        Page<Order> pageParam = new Page<>(page, pageSize);
        Page<Order> orderPage = baseMapper.selectOrderPage(pageParam, userId, status);
        
        Page<OrderVO> resultPage = new Page<>();
        BeanUtils.copyProperties(orderPage, resultPage, "records");
        
        List<OrderVO> orderVOList = orderPage.getRecords().stream().map(order -> {
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(order, orderVO);
            
            // 设置订单状态描述
            orderVO.setStatusDesc(getStatusDesc(order.getStatus()));
            
            // 查询订单项
            List<OrderItemVO> orderItemVOList = orderItemMapper.selectOrderItemsByOrderId(order.getId());
            orderVO.setOrderItems(orderItemVOList);
            
            return orderVO;
        }).collect(Collectors.toList());
        
        resultPage.setRecords(orderVOList);
        return resultPage;
    }
    
    /**
     * 生成订单编号
     *
     * @return 订单编号
     */
    private String generateOrderNo() {
        // 时间戳 + 随机数
        String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        String random = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 6);
        return timestamp + random;
    }
    
    /**
     * 获取订单状态描述
     *
     * @param status 状态码
     * @return 状态描述
     */
    private String getStatusDesc(Integer status) {
        switch (status) {
            case 0:
                return "待付款";
            case 1:
                return "待发货";
            case 2:
                return "待收货";
            case 3:
                return "已完成";
            case 4:
                return "已取消";
            default:
                return "未知状态";
        }
    }
} 